package com.example.nfcschool;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.ActionBar;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Typeface;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class TListActivity extends Activity implements OnClickListener,OnItemClickListener {

	final int TLIST = 1;
	long time = 0;

	ArrayList<ListDataVO> al;
	ArrayList<ListDataVO> arr;
	ListView lv;
	SmemberVO d;
	TextView tv;

	private NfcAdapter mNfcAdapter; // NfcAdapter 를 선언
	private PendingIntent mPendingIntent; // PendingIntent 선언
	private IntentFilter[] mIntentFilters; // 이건.. 필터라고 되어있으니, 받은 NdefMessage를
											// 적당히 필터해주는 역할인 듯?

	String text = "";
	SRecordVO rvo;
	
	SharedPreferences sp;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_tlist);
		
		sp = getSharedPreferences("teachdata", Activity.MODE_PRIVATE);
		
		// ActionBar제거한다.
		ActionBar actionBar = getActionBar();
        actionBar.hide();
		
		tv=(TextView)findViewById(R.id.textView1);
		lv = (ListView) findViewById(R.id.tlistview);
		lv.setOnItemClickListener(this);
		list();

		mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
		Intent intent = new Intent(this, getClass())
				.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		mPendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

		// set an intent filter for all MIME data
		IntentFilter ndefIntent = new IntentFilter(
				NfcAdapter.ACTION_NDEF_DISCOVERED);
		try {
			ndefIntent.addDataType("*/*");
			mIntentFilters = new IntentFilter[] { ndefIntent };
		} catch (Exception e) {
			Log.e("TagDispatch", e.toString());
		}

	}

	@Override
	protected void onResume() {
		super.onResume();
		if (mNfcAdapter != null) {
			mNfcAdapter.enableForegroundDispatch(this, mPendingIntent,
					mIntentFilters, null);
		}
		list();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		if (mNfcAdapter != null) {
			mNfcAdapter.disableForegroundDispatch(this);
		}
	}

	@Override
	public void onBackPressed() {
		if (System.currentTimeMillis() >= time + 2000) {
			Toast.makeText(this, "한 번 더 누르면 종료됩니다.", Toast.LENGTH_SHORT).show();
			time = System.currentTimeMillis();
		} else {
			finishAffinity();
//			finish();
			
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		Intent intent = null;
		switch (id) {
		case R.id.LOGOUT:
			FileOutputStream fos = null;
			try {
				fos = openFileOutput("auto", Activity.MODE_PRIVATE);
				String data = "0";
				fos.write(data.getBytes());
				fos.close();
			} catch (Exception ex) {
				Log.e("파일 save 에러", ex.toString());
			}
			finish();
			intent = new Intent(this, MainActivity.class);
			startActivity(intent);
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	public void list() {
		
//		SDBHelper db = new SDBHelper(this, "1myDB", null, 1);
//		al = db.selectList();
		new loadJsp().execute();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {

		ListDataVO d = arr.get(position);
//		Toast.makeText(this, d.getTel(), 2000).show();

		Intent intent = new Intent(this, TViewActivity.class);
		intent.putExtra("tel", d.getTel());
		
		startActivity(intent);

	}

	// Font_List
	@Override
	protected void onStart() {
		Typeface typeFace = Typeface.createFromAsset(getAssets(), "white.ttf");
		TextView tv1 = (TextView) findViewById(R.id.textView1);

		tv1.setTypeface(typeFace);

		super.onStart();
	}

	// onNewIntent 라는 것은.. 현재 액티비티가 재 호출 될때 발생한다.
	// onCreate가 새로 생성될 때 일어나는 이벤트라고 하면, onNewIntent는 현재 액티비티가 생성은 되어 있는데, 재호출
	// 될때 동작한다. onCreate 에서 intent 선언할 때
	// intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP) 와 같이 플래그를 주게 되면 발생한다.
	
	@Override
	public void onNewIntent(Intent intent) {
		Log.d("intent받았다.","intent 들어왔다.");
		try{
		Parcelable[] rawMsgs = intent
				.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
		Log.d("NFC 읽었따.","NFC데이터는 받았다.");
		if (rawMsgs != null) {
			NdefMessage msg = (NdefMessage) rawMsgs[0];
			NdefRecord[] rec = msg.getRecords();

			byte[] bt = rec[0].getPayload();
			text = new String(bt);

//			SDBHelper db = new SDBHelper(this, "1myDB", null, 1);
//			d = db.select(text);

			Log.d("페이로드로 값을 받은 텍스트"+text,text);
//			Toast.makeText(this, "텍스트"+text, 2000).show();
			new RecentRecordJsp().execute();
//			Log.d("페이로드로 값을 받은 텍스트2"+text,text);
//			if(d!=null){
//				new loadJsp().execute();
//			}
		}
		}catch(Exception e){
			Log.d("onNewIntent Catch",e.toString());
		}
	}
//*********************************************************************************************
	public class loadJsp extends AsyncTask<Void, String, Void> {
		
		URL url = null;
		String tag = "";
		StringBuilder sb=new StringBuilder();
		@Override
		protected Void doInBackground(Void... param) {
			
			try {
				Calendar calender = Calendar.getInstance();
				java.util.Date date = calender.getTime();
				String today = (new SimpleDateFormat("yyyy/MM/dd").format(date));
				
				Log.d("여기는 loadJsp","LoadJsp는 왔어");
				HttpClient client = new DefaultHttpClient();
				String postURL = "http://192.168.0.7:8888/AndroidCheck/SelectList.jsp";
				HttpPost post = new HttpPost(postURL);

				ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
				
				params.add(new BasicNameValuePair("grade", sp.getString("grade", "1-2")));
				params.add(new BasicNameValuePair("today", today));
				
				UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
				post.setEntity(ent);
				HttpResponse responsePOST = client.execute(post);
				HttpEntity resEntity = responsePOST.getEntity();
				
				if (resEntity != null) {
//					Log.i("RESPONSE", EntityUtils.toString(resEntity));
					sb.append(EntityUtils.toString(resEntity));
				}
				client.getConnectionManager().shutdown(); //추가된 코드.
				
				
				
				
				
				XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); 
	    		factory.setNamespaceAware(true);             
	    		XmlPullParser xpp = factory.newPullParser(); 
	    		xpp.setInput(new StringReader(sb.toString()));   
	    		int eventType = xpp.getEventType();
	    		arr = new ArrayList<ListDataVO>();
	    		ListDataVO m=null;
	    		while(eventType != XmlPullParser.END_DOCUMENT){//현재 이벤트 타입이 END_DOCUMENT를 만날때 까지 반복.
	    			
		    		switch(eventType){
	    			case XmlPullParser.START_TAG :  // 이벤트 타입에 START_TAG 라면.
	    				tag = xpp.getName(); // 태그 이름을 추출함.
	    				if(tag.equals("listdata")){
	    					m = new ListDataVO();
	    				}else if(tag.equals("irum")) {
	    					m.setIrum(xpp.nextText());
	    				}else if(tag.equals("sno")){
	    					m.setSno(xpp.nextText());
	    				}else if(tag.equals("instate")){
	    					m.setInstate(xpp.nextText());
	    				}else if(tag.equals("intime")){
	    					m.setIntime(xpp.nextText());
	    				}else if(tag.equals("outstate")){
	    					m.setOutstate(xpp.nextText());
	    				}else if(tag.equals("outtime")){
	    					m.setOuttime(xpp.nextText());
	    				}else if(tag.equals("tel")){
	    					m.setTel(xpp.nextText());
	    				}
	    			
	    				break;
	    			
	    			case XmlPullParser.END_TAG :
	    				tag = xpp.getName();
	    				if(tag.equals("listdata")){
	    					arr.add(m); 
	    				}
	    				break;
	    			}
	    			eventType = xpp.next();
	    		}
			} catch (Exception e) {
				Log.e("TList Async Err",e.toString());
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			tv.setText("학생 정보");
			Log.e("listend?", "end?");
			Log.e("arr.size", arr.size()+"");
			MyAdapter adapter = new MyAdapter(TListActivity.this, R.layout.list_file, arr);
			Log.d("Adapter 후에,,,,","Adapter 뒤에 에러나냐??");
			lv.setAdapter(adapter);
			super.onPostExecute(result);
		}
		@Override
		protected void onPreExecute() {
			tv.setText("불러오는 중..");
			super.onPreExecute();
		}
	}

	

	// ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡWebDB*******************************
	public class InsertRecordJsp extends AsyncTask<Void, String, Void> {
		@Override
		protected Void doInBackground(Void... param) {
			
			Calendar calender = Calendar.getInstance();
			java.util.Date date = calender.getTime();
			String today = (new SimpleDateFormat("yyyyMMdd:HHmmss").format(date));
			
			try {
				HttpClient client = new DefaultHttpClient();
				String postURL = "http://192.168.0.7:8888/AndroidCheck/InsertRecord.jsp";
				HttpPost post = new HttpPost(postURL);

				ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
				
				
				//***************************작***********업***************중***********
				
				params.add(new BasicNameValuePair("tel", text));
				params.add(new BasicNameValuePair("attend", rvo.getAttend()));
				params.add(new BasicNameValuePair("instate", rvo.getInstate()));
				params.add(new BasicNameValuePair("intime", rvo.getIntime()));
				params.add(new BasicNameValuePair("outstate", rvo.getOutstate()));
				params.add(new BasicNameValuePair("outtime", rvo.getOuttime()));
				params.add(new BasicNameValuePair("time", today));
				
				
				UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
				post.setEntity(ent);
				HttpResponse responsePOST = client.execute(post);
				HttpEntity resEntity = responsePOST.getEntity();

				if (resEntity != null) {
					Log.i("RESPONSE", EntityUtils.toString(resEntity));
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			Log.e("joinend?", "end?");
			list();
			super.onPostExecute(result);
		}
	}
	

	//*********************************************************************************************
	
	public class RecentRecordJsp extends AsyncTask<Void, String, Void> {
		
		String tag="";
		StringBuilder sb=new StringBuilder();
	
		@Override
		protected Void doInBackground(Void... param) {
			
			try {
				
				Log.e("pre","pre");
				
				HttpClient client = new DefaultHttpClient();
				String postURL = "http://192.168.0.7:8888/AndroidCheck/RecentRecord.jsp";
				HttpPost post = new HttpPost(postURL);

				ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
				
				params.add(new BasicNameValuePair("tel", text));
				
				UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
				post.setEntity(ent);
				HttpResponse responsePOST = client.execute(post);
				HttpEntity resEntity = responsePOST.getEntity();
				
				if (resEntity != null) {
//					Log.i("RESPONSE", EntityUtils.toString(resEntity));
					sb.append(EntityUtils.toString(resEntity));
				}
				client.getConnectionManager().shutdown(); //추가된 코드.
				
				
				
				
				// 데이터 받기
				XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); 
	    		factory.setNamespaceAware(true);             
	    		XmlPullParser xpp = factory.newPullParser(); 
	    		xpp.setInput(new StringReader(sb.toString()));   
	    		int eventType = xpp.getEventType();
	    		
	    		
	    		while(eventType != XmlPullParser.END_DOCUMENT){//현재 이벤트 타입이 END_DOCUMENT를 만날때 까지 반복.
	    			
		    		switch(eventType){
	    			case XmlPullParser.START_TAG :  // 이벤트 타입에 START_TAG 라면.
	    				tag = xpp.getName(); // 태그 이름을 추출함.
	    				if(tag.equals("srecord")){
	    					rvo = new SRecordVO();
	    				}else if(tag.equals("tel")){
	    					rvo.setTel(xpp.nextText());
	    				}else if(tag.equals("attend")){
	    					rvo.setAttend(xpp.nextText());
	    				}else if(tag.equals("instate")){
	    					rvo.setInstate(xpp.nextText());
	    				}else if(tag.equals("intime")){
	    					rvo.setIntime(xpp.nextText());
	    				}else if(tag.equals("outstate")){
	    					rvo.setOutstate(xpp.nextText());
	    				}else if(tag.equals("outtime")){
	    					rvo.setOuttime(xpp.nextText());
	    				}
	    				break;
	    			
	    			}
	    				
	    			eventType = xpp.next();
	    		}
				
	    		
			} catch (Exception e) {
				Log.e("SView Async Err",e.toString());
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			
			Log.e("TList RecentRecord", "end?");
			if(rvo!= null){
				Log.d("rvo가 널은 아니야","널 아니라고 ");
				new InsertRecordJsp().execute();
			}
			else{
				Log.e("RecentRecord Data가 ","엄따!!!!!!!");
			}
			super.onPostExecute(result);
		}
	}
	
	
	
}
